<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>产品详情</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <!-- 引入jQuery -->
    <link rel="stylesheet" href="css/product-detail.css">
    <!-- 引入CSS -->

</head>

<body>
<header>
    <h1>产品详情页面</h1>
    <nav>
        <ul>
            <li><a href="home.html">返回首页</a></li>
            <li><a href="#" onclick="checkLogin()">购物车</a></li>
        </ul>
    </nav>
</header>

<main>
    <div class="product-detail-container">
        <div class="product-images">
            <img src="" alt="产品图片" id="productImage">
        </div>
        <div class="product-info">
            <h2 class="product-name">加载中...</h2>
            <p class="product-price">0.00</p>
            <div class="product-details">加载中...</div>
            <div class="select-address">
                <label for="address">选择收获地址：</label>
                <select id="address">
                    <!-- 地址选项将通过JavaScript动态填充 -->
                </select>
            </div>
            <div class="add-to-cart">
                <button id="addToCart" onclick="add()">加入购物车</button>
            </div>
        </div>
    </div>
    <div class="comment-section">
        <div class="filter-buttons">
            <button onclick="filterComments('all')">全部</button>
            <button onclick="filterComments('positive')">好评</button>
            <button onclick="filterComments('neutral')">中评</button>
            <button onclick="filterComments('negative')">差评</button>
        </div>
        <div id="commentsList">
            <!-- 评论内容将通过JavaScript动态填充 -->
        </div>
    </div>
</main>

<footer>
    <p>&copy; 2024 我的电商网站</p>
</footer>

<script>
    // 检查用户是否登录
    function checkLogin() {
        $.ajax({
            url: "/user/get-user",
            type: "get",
            success: function (result) {
                console.log(result);
                if (result.state == 401) {
                    if (confirm("你尚未登录，是否前往登录？")) {
                        location.href = "login.html";
                    }
                }
                if (result.state == 200) {
                    location.href = "shoppingcart.html";
                }
            },
            error: function (err) {
                if (err.status == 401) {
                    alert("当前用户未登录，你即将回到首页");
                    location.href = "home.html";
                }
            }
        });
    }

    const urlParams = new URLSearchParams(window.location.search);
    const productId = urlParams.get('id'); // 获取 productId
    $.ajax({
        url: "/product/detail",
        type: "GET",
        dataType: "json",
        data: {
            id: productId
        },
        success: function (product) {
            updateProductDetails(product);
            getComments(); // 获取产品评论
        },
        error: function () {
            alert("获取产品详情失败");
        }
    });

    // 获取地址信息
    getAddress();
    const addressSelectElement = document.getElementById('address');
    function getAddress() {
        $.ajax({
            url: "/user/get-address",
            type: "GET",
            dataType: "json",
            success: function (address) {
                addressSelectElement.innerHTML = `<option value="${address.data.address}">${address.data.address}</option>`;
            },
            error: function () { }
        });
    }

    function updateProductDetails(product) {
        const nameElement = document.querySelector('.product-name');
        const productPriceElement = document.querySelector('.product-price');
        const productDetailsElement = document.querySelector('.product-details');
        const productImageElement = document.getElementById('productImage');

        nameElement.textContent = product.data[0].name;
        productPriceElement.textContent = `￥${product.data[0].price}`;
        productDetailsElement.textContent = product.data[0].details;
        productImageElement.src = product.data[0].img;
    }

    // 获取产品评论
    function getComments() {
        $.ajax({
            url: `/comment/get-all`,
            type: "GET",
            dataType: "json",
            data: {
                pid: productId
            },
            success: function (comments) {
                console.log(comments);
                displayComments(comments.data);
            },
            error: function () {

                alert("获取评论失败");
            }
        });
    }
    let currentUserId = null;
    $.ajax({
        url: "/user/get-user",
        type: "GET",
        success: function (result) {
            if (result.state == 200) {
                currentUserId = result.data.id; // 假设用户信息包含id
            }
        }
    });

    function displayComments(comments) {
        const commentsList = document.getElementById('commentsList');
        commentsList.innerHTML = ''; // 清空评论列表

        comments.forEach(comment => {
            const commentDiv = document.createElement('div');
            const editButton = (comment.uid === currentUserId)?
                `<button class="edit-comment-button" onclick="location.href='comment.html?uid=${comment.uid}&pid=${comment.pid}&traceNo=${comment.traceNo}'">修改评论</button>` : '';
            commentDiv.className = 'comment';
            commentDiv.innerHTML = `
            <div class="comment-header">
                <span class="comment-username">用户: ${comment.username}</span>
                <span class="comment-time">时间: ${new Date(comment.createTime).toLocaleString()}</span>
                <span class="comment-rating">评分: ${'★'.repeat(comment.rating)}</span>
                ${editButton}
            </div>
            <div class="comment-content">${comment.content}</div>
            <hr class="comment-separator">
        `;
            commentsList.appendChild(commentDiv);
        });
    }


    function filterComments(type) {
        // 移除所有按钮的.active类
        const buttons = document.querySelectorAll('.filter-buttons button');
        buttons.forEach(button => {
            button.classList.remove('active');
        });

        // 为当前点击的按钮添加.active类
        const currentButton = Array.from(buttons).find(button => {
            return button.textContent === (type === 'all' ? '全部' :
                type === 'positive' ? '好评' :
                    type === 'neutral' ? '中评' :
                        '差评');
        });
        if (currentButton) {
            currentButton.classList.add('active');
        }
        $.ajax({
            url: `/comment/get-by-rating`,
            type: "GET",
            dataType: "json",
            data: {
                rating: type,
                pid: productId
            },
            success: function (comments) {
                displayComments(comments.data);
            },
            error: function () {
                alert("获取评论失败");
            }
        });
    }

    function add() {
        $.ajax({
            url: "/product/add",
            type: "get",
            dataType: "json",
            data: {
                pid: productId
            },
            success: function (product) {
                console.log(product);
                if (product.state == 200) {
                    const alertBox = document.createElement('div');
                    alertBox.className = 'alert-box'; // 添加样式类
                    alertBox.textContent = "添加成功";
                    document.body.appendChild(alertBox);

                    setTimeout(() => {
                        alertBox.classList.add('fade-out'); // 加入渐变消失效果
                        setTimeout(() => {
                            alertBox.remove(); // 从DOM中移除
                        }, 500);
                    }, 1000);
                    return;
                } else {
                    alert(product.msg);
                }
            },
            error: function () {
                alert("请先登陆");
                location.href = "login.html";
            }
        });
    }
</script>
</body>

</html>